import localRoutes from '@/router/main'
import router from '@/router'

// 映射静态路由
export default function mapMenus(menus: any[]) {
  menus.forEach((menu) => addRouteForMenu(menu))
}

export let firstMenu = null
function addRouteForMenu(menu: any) {
  // 处理当前菜单项的路由
  const route = localRoutes.find((item) => item.path === menu.path)
  if (route) {
    router.addRoute('main', route)
  }
  // 记录第一个菜单
  if (!firstMenu && route) firstMenu = menu

  // 如果有子菜单，递归处理子菜单
  if (menu.children && menu.children.length) {
    menu.children.forEach((child: any) => addRouteForMenu(child))
  }
}

/**
 * 根据路径匹配需要菜单的id
 * @param path 路径
 * @param userMenus 用户所有菜单
 * @returns 菜单
 */
export function mapPathToMenu(path: string, userMenus: any[]): any {
  for (const menu of userMenus) {
    if (menu.path === path) {
      return menu
    }
    if (menu.children) {
      const foundMenu = mapPathToMenu(path, menu.children)
      if (foundMenu) {
        return foundMenu
      }
    }
  }
}

interface IBreadcrumbs {
  name: string
  path: string
}
// 面包屑数据
export function mapPathToBreadcrumbs(path: string, userMenus: any[]) {
  const breadcrumbs: IBreadcrumbs[] = []

  for (const menu of userMenus) {
    if (menu.path === path) {
      breadcrumbs.push({ name: menu.name, path: menu.path })
    }
    if (menu.children) {
      for (const submenu of menu.children) {
        if (submenu.path === path) {
          breadcrumbs.push({ name: menu.name, path: menu.path })
          breadcrumbs.push({ name: submenu.name, path: submenu.path })
        }
      }
    }
  }
  return breadcrumbs
}
